package com.boot.tool.go.service;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.boot.tool.common.exception.AppServiceException;
import com.boot.tool.go.config.GoFastdfsConfig;
import com.boot.tool.go.vo.GoFast;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

import java.rmi.ServerException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: Andy Li
 * @Date: 2019/3/1 17:56
 * @Version 1.0.0
 */
@Slf4j
@Service
public class GoService {

    @Autowired
    private GoFastdfsConfig goFastdfsConfig;

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/png", "image/jpeg");

    public String uploadImage(MultipartFile multipartFile) {


        // 获取文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        // 文件格式（后缀）
        String contentType = multipartFile.getContentType();
        if (!CONTENT_TYPES.contains(contentType)){
            log.info("文件格式不合法：{}", originalFilename);
            throw AppServiceException.SERVER_IO_FORMAT_EXCEPTION;

        }
        //转换文件 MultipartFile 转为 File 方便传输。
        File file = new File(IdUtil.createSnowflake(1,1).nextId() +originalFilename);
        try {
            //看看是不是图片。
            BufferedImage bufferedImage = ImageIO.read(multipartFile.getInputStream());
            if (bufferedImage == null) {
                log.info("文件内容不合法：{}", originalFilename);
                throw AppServiceException.SERVER_IO_WORK_EXCEPTION;
            }

            FileUtil.writeFromStream(multipartFile.getInputStream(), file);

        } catch (Exception e) {
            throw AppServiceException.SERVER_IO_WORK_EXCEPTION;
        }
        //封装传入的参数。
            Map<String, Object> map = MapUtil.newHashMap(4);
        map.put("output", "json");
        //使用日期作为路径
        map.put("path", cn.hutool.core.date.DateUtil.format(new Date(),"yyyy/MM"));
        map.put("scene", "image");
        map.put("file", file);
        //如果传入的参数没有url也会报错
        try {
            String post = HttpUtil.post(goFastdfsConfig.upload, map);
            GoFast goFast = JSONUtil.toBean(post, GoFast.class);
            log.info("发送文件返回的结果{}", goFast.toString());
            boolean delete = file.delete();
            if (delete){
                log.info("文件转化已经完成");
            }
            return goFast.getUrl();
        } catch (Exception e) {
            log.info("文件服务器地址不对");
            throw AppServiceException.SERVER_NO_FOUND_EXCEPTION;
        }
    }
}


